package com.SDU.policedispatch.controller.user;


import com.SDU.policedispatch.service.privilege.GetPrivilegeService;
import com.SDU.policedispatch.service.user.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class UserAccountController {

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private GetPrivilegeService getPrivilegeService;

    @ResponseBody
    @PostMapping("/api/register")
    Map<String, String> Register(@RequestBody Map<String, String> map) {
        Map<String, String> res = new HashMap<>();
        String username = map.get("username");
        String password = map.get("password");
        String confirmedPassword = map.get("confirmed_password");
        String type = map.get("type");
        String departmentId = map.get("department_id");
        int Type, DepartmentId;
        try {
            Type = Integer.parseInt(type);
            DepartmentId = Integer.parseInt(departmentId);
        } catch (Exception e) {
            res.put("error_message", "数字转换错误");
            return res;
        }

        if(username == null || password == null) {
            res.put("error_message", "用户名或密码不能为空");
            return res;
        }
        username = username.trim();
        password = password.trim();
        confirmedPassword = confirmedPassword.trim();
        if(username.length() < 1 || username.length() > 30) {
            res.put("error_message", "用户名长度不符合规范");
            return res;
        }
        if(password.length() < 1 || confirmedPassword.length() < 1) {
            res.put("error_message", "密码不能为空");
            return res;
        }
        if(!password.equals(confirmedPassword)) {
            res.put("error_message", "两次密码不同");
            return res;
        }
        if(password.length() < 6 ) {
            res.put("error_message", "密码长度小于6");
            return res;
        }
        return userAccountService.UserRegister(DepartmentId, username, password, Type);
    }

    @ResponseBody
    @PostMapping("/api/login")
    Map<String, String> GetToken(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        return userAccountService.UserLogin(username, password);
    }

    @PostMapping("/api/info")
    Map<String, String> GetInfo() {
        return userAccountService.UserInfo();
    }

    @GetMapping("/api/permission")
    Map<String, Object> GetPermission() {
        return getPrivilegeService.GetP();
    }
}
